package com.k.demo.websocket;

import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;


@ServerEndpoint(value = "/wss")
@Component
public class OrderRemindServer {

	private static CopyOnWriteArraySet<Session> webSocketSet = new CopyOnWriteArraySet<Session>();

	// 这个方法会在建立连接的时候自动调用
	@OnOpen
	public void open(Session session) {
		webSocketSet.add(session);
		System.out.println("有新的连接, 总数:" + webSocketSet.size());
	}

	// 关闭连接的时候被调用
	@OnClose
	public void close(Session session) {
		webSocketSet.remove(session);
		System.out.println("close");
	}

	// 发送信息的时候,自动调用
	@OnMessage
	public void message(String msg) {
		System.out.println("OnMessage");
		for (Session session : webSocketSet) {
			System.out.println(msg);
			try {
				session.getBasicRemote().sendText(msg);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	// 发生错误的时候,自动调用
	@OnError
	public void error(Session session, Throwable error) {
		System.out.println("error");
	}

}
